#include <engine.h>
#include <QGraphicsTextItem>


GRenderer::GRenderer()
{
    m_pWindow = NULL;
//    m_pGuiFps = NULL;
//    m_bShowFps = false;
}

GRenderer::~GRenderer()
{
}

//void GRenderer::ShowFps(bool bShow)
//{
//    if(bShow)
//    {
//        if(!m_pGuiFps)
//        {
//            m_pGuiFps = new QGraphicsTextItem;
//            m_pView->addItem(m_pGuiFps);
//        }
//    }
//    else
//    {
//        if(m_pGuiFps)
//        {
//            delete m_pGuiFps;
//            m_pGuiFps = NULL;
//        }
//    }
//}

bool GRenderer::RendererInitialize(GWindow* pWnd)
{
    if(!pWnd)
        return false;

    m_pWindow = pWnd;
    return true;
}

void GRenderer::RendererStart()
{
    if(m_pWindow)
       m_pWindow->show();
}

void GRenderer::RendererEnd()
{
}

void GRenderer::Render(double elapsed)
{
	GAnimates* pAniList = GEngine::GetGame()->GetAnimateObjects();
	if(!pAniList || pAniList->size() <= 0)
		return;
	
	GAnimates finish;	
	GAnimates_itor it = pAniList->begin();
	GAnimates_itor end = pAniList->end();
	while(it != end)
	{
		GAnimate *pAni = *it;
		Q_ASSERT(pAni);
		
		QTime& start = pAni->GetStartTime();
		if(start.isNull())
			pAni->SetStart();
		else
		{	
			/*int a = start.msecsTo(QTime::currentTime());
			double b = pAni->GetDuration();
			qDebug() << "a" << a << "b" << b;*/

			double e = start.msecsTo(QTime::currentTime());
			//if(pAni->IsStop() || e > pAni->GetDuration())
			if(e > pAni->GetDuration())
			{
				pAni->Finish();
				it = pAniList->erase(it);
				finish.push_back(pAni);
				//qDebug() << (pAni->IsStop() ? "stop" : "finish");
				continue;
			}
			else
			{
				pAni->DoAnimate(e);
			}
		}

		++it;
	}

	GAnimates_itor itor;
	for(itor = finish.begin(); itor != finish.end(); itor++)
    {
		GAnimate* pAni = *itor;
		delete pAni;
    }
}
